from time import sleep

from qturboframe.lib.utils.by import By
from qturboframe.lib.report.log import logger
from qturboframe.lib.utils.check import CheckBasic
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.public_ui.base_element import BaseElement
from qturboframe.lib.utils.CustomError.custom_error import CustomError


class Button(BaseElement, CheckBasic):
    '''hui的按钮操作'''
    def __init__(self, element_para, father=None, timeout=5, index=1):
        if isinstance(element_para, dict) and By.TEXT in list(element_para.keys())[0]:
            xpath_button = ".//button[normalize-space(text())='{}' and not(contains(@style,'display: none'))]".format(element_para.get(By.TEXT))
            xpath_a = ".//a[contains(normalize-space(text()),'{}') and not(contains(@style,'display: none')) or normalize-space(@title)='{}']".format(element_para.get(By.TEXT),element_para.get(By.TEXT))
            xpath_button_span = ".//button/span[@title='{}' or normalize-space(text())='{}']/..".format(element_para.get(By.TEXT), element_para.get(By.TEXT))
            xpath_input = ".//input[@value='{}']".format(element_para.get(By.TEXT))
            xpath_label = ".//label[contains(text(),'{}')]".format(element_para.get(By.TEXT))
            xpath_div = ".//div[contains(text(),'{}')]".format(element_para.get(By.TEXT))
            xpath_span = ".//span[@title='{}' or normalize-space(text())='{}']".format(element_para.get(By.TEXT),element_para.get(By.TEXT))
            xpath = xpath_button + " | " + xpath_a + " | " + xpath_button_span + " | " + xpath_input + " | " + xpath_label + " | " + xpath_div + " | " + xpath_span
            buttons = father.find_elements_by_attribute(By.XPATH, xpath, timeout=timeout)
            if len(buttons)>0:
                self.buttons = buttons
            else:
                #在上面查找button中包含span的控件，当没找到合适的控件后，查找符合要求的span控件
                xpath_span = ".//span[@title='{}' or normalize-space(text())='{}']".format(element_para.get(By.TEXT), element_para.get(By.TEXT))
                buttons = father.find_elements_by_attribute(By.XPATH, xpath_span, timeout=timeout)

            if len(buttons) != 0:
                super().__init__(buttons[index-1], father, timeout)
                return

            message = "没有找到名字为'{}'的按钮".format(element_para)
            raise SeleniumError(CustomError.Error_EQ03001000_Cannot_Find_Element, message)
        else:
            super().__init__(element_para, father, timeout)

    def click(self):
        '''
        hui的按钮点击

        :Example:
         - 例: button.click()
        '''
        button_text = self._element.text
        if not button_text:
            button_text = self._element.get_attribute('title')
        logger.info('点击按钮：' + button_text)
        self._element.secure_click()

    def js_click(self):
        '''
        hui的按钮js点击

        :Example:
         - 例: button.js_click()
        '''
        button_text = self._element.text
        if not button_text:
            button_text = self._element.get_attribute('title')
        logger.info('点击按钮：' + button_text)
        self._driver.execute_script("arguments[0].click();", self._element)

    def dropdown_click(self, dropdown_text):
        '''
        hui的dropdown按钮点击

        :Args:
         - dropdown_text: dropdown按钮的文本

        :Example:
         - 例: button.dropdown_click('删除')
        '''
        button_text = self._element.text
        logger.info('点击按钮：' + button_text)
        # 查找按钮组件
        select_father_div = self._element.find_element_by_attribute(
            'xpath', './/ancestor::button/parent::div/parent::div', timeout=0.1)
        self._element.secure_click()
        timeout = 0
        while timeout < self.timeout:
            # 保持鼠标悬停在按钮上
            self._element.move_to()
            # 查找下拉按钮
            select_li_btn = select_father_div.exist(
                'css selector', 'li.h-dropdown-item', 'text:' + dropdown_text, timeout=0.1)
            if select_li_btn:
                break
            else:
                timeout += 0.1
                sleep(0.1)
        else:
            message = '未找到按钮：{}！'.format(dropdown_text)
            raise SeleniumError(CustomError.Error_EQ03001000_Cannot_Find_Element, message)
        logger.info('点击按钮：' + dropdown_text)
        select_li_btn.secure_click()

    def is_enable(self):
        '''
        判断hui按钮是否可用

        :Returns:
            可用则返回True, 不可用则返回False

        :Example:
         - 例: button.is_enable()
        '''
        if self._element.is_enabled():
            return True
        else:
            return False

    def check_enable(self, state='disable'):
        '''
        hui按钮是否可用校验

        :Attributes:
         - flag: 校验标记，表示需要校验的按钮状态，display表示禁用，enable表示可用

        :Raises:
            不可用则抛出SeleniumError异常

        :Example:
         - 例: button.check_enable('enable')
        '''
        if state == 'disable':
            if self._element.is_enabled():
                raise SeleniumError('按钮未禁用！')
        else:
            if not self._element.is_enabled():
                raise SeleniumError('按钮已禁用！')
